package cn.org.wangchangjiu.table2entity.util;

import cn.org.wangchangjiu.table2entity.model.MapperXml;
import cn.org.wangchangjiu.table2entity.model.RepositoryInfo;
import cn.org.wangchangjiu.table2entity.model.TableInfo;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.jetbrains.annotations.NotNull;

import java.io.StringWriter;
import java.util.Date;

/**
 * @Classname VelocityUtils
 * @Description
 * @Date 2023/5/8 17:00
 * @Created by wangchangjiu
 */
public class VelocityUtils {

    /**
     *  生成 entity
     * @param tableInfo
     * @return
     */
    public static String generateEntity(TableInfo tableInfo, String templatePath) {

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tableInfo", tableInfo);
        velocityContext.put("date", MyDateUtils.dateToString(new Date()));

        return generateCode(velocityContext, templatePath);
    }

    /**
     *  生成
     * @param repositoryInfo
     * @return
     */
    public static String generateDao(RepositoryInfo repositoryInfo, String templatePath) {

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("daoInfo", repositoryInfo);
        velocityContext.put("date", MyDateUtils.dateToString(new Date()));

        return generateCode(velocityContext, templatePath);
    }

    public static String generateMapperXml(MapperXml mapperXml, String templatePath) {

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("mapperXml", mapperXml);

        return generateCode(velocityContext, templatePath);
    }

    @NotNull
    private static String generateCode(VelocityContext velocityContext, String templatePath) {
        final ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(VelocityUtils.class.getClassLoader());

        //实例化
        VelocityEngine velocityEngine = new VelocityEngine();

        //关闭日志
        velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();

        StringWriter writer = new StringWriter();
        //生成代码
        velocityEngine.getTemplate(templatePath).merge(velocityContext, writer);

        String code = writer.toString();

        Thread.currentThread().setContextClassLoader(oldContextClassLoader);
        return code.replaceAll("\r\n", "\n");
    }

}
